package com.lgq.cfw.service.impl;

import com.lgq.cfw.bean.TableAdvertisement;
import com.lgq.cfw.bean.example.TableAdvertisementExample;
import com.lgq.cfw.bean.example.TableAdvertisementExample.Criteria;
import com.lgq.cfw.dao.TableAdvertisementMapper;
import com.lgq.cfw.service.AdvertisementService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Lin
 * @date 2019-02-14 20:46
 **/
@Service
public class AdvertisementServiceImpl implements AdvertisementService {


  @Autowired
  TableAdvertisementMapper tableadvertisementMapper;

  /**
   * 获取所有广告
   * @return list
   */
  @Override
  public List<TableAdvertisement> getAll() {
    return tableadvertisementMapper.selectByExample(null);
  }

  /**
   * 添加广告
   * @param tableAdvertisement 前台出入的广告
   * @return 是否成功
   */
  @Override
  public boolean add(TableAdvertisement tableAdvertisement) {
    int row=0;
    try{
      row=tableadvertisementMapper.insertSelective(tableAdvertisement);
    }catch (Exception e){
      e.printStackTrace();
      return false;
    }
    return row!=0;
  }

  /**
   * 删除广告
   * @param advertisementDeleteIdString 广告id字符串
   * @return 是否成功
   */
  @Override
  public boolean delete(String advertisementDeleteIdString) {
    List<Integer> advertisementIdList = new ArrayList<>();
    if (!advertisementDeleteIdString.contains("-")) {
      try {
        tableadvertisementMapper.deleteByPrimaryKey(Integer.parseInt(advertisementDeleteIdString));
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
      return true;
    } else {
      String[] singleAdvertisementIdStringArray = advertisementDeleteIdString.split("-");
      for (String singleAdvertisementIdString : singleAdvertisementIdStringArray) {
        Integer singleAdvertisementIdInteger = Integer.parseInt(singleAdvertisementIdString);
        advertisementIdList.add(singleAdvertisementIdInteger);
      }
      TableAdvertisementExample tableAdvertisementExample = new TableAdvertisementExample();
      Criteria criteria = tableAdvertisementExample.createCriteria();
      criteria.andIdIn(advertisementIdList);
      try {
        tableadvertisementMapper.deleteByExample(tableAdvertisementExample);
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
      return true;
    }
  }

  /**
   * 更新广告信息
   * @param tableAdvertisement 前台传入的广告封装信息
   * @return 处理信息
   */
  @Override
  public boolean update(TableAdvertisement tableAdvertisement) {
    try {
    tableadvertisementMapper.updateByPrimaryKeySelective(tableAdvertisement);
    }catch (Exception e){
      e.printStackTrace();
      return false;
    }
    return true;
  }
}
